package com.xiaobaibai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.bo.OrderDelayItem;
import com.xiaobaibai.common.OrderCommon;
import com.xiaobaibai.common.OrderEnum;
import com.xiaobaibai.common.PayEnum;
import com.xiaobaibai.controller.OrderController;
import com.xiaobaibai.dao.PaymentRecordDao;
import com.xiaobaibai.entity.Order;
import com.xiaobaibai.entity.PaymentRecord;
import com.xiaobaibai.service.IOrderService;
import com.xiaobaibai.service.IPaymentRecordService;
import com.xiaobaibai.units.OrderAcceptDelayQueueUnit;
import com.xiaobaibai.units.pay.BigDecimalUtil;
import com.xiaobaibai.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-11-20
 */
@Service
@Slf4j
public class PaymentRecordServiceImpl extends ServiceImpl<PaymentRecordDao, PaymentRecord> implements IPaymentRecordService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private OrderAcceptDelayQueueUnit orderAcceptDelayQueueUnit;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${autoConfirmGoodsMin}")
    private Integer autoConfirmGoodsMin;

    @Override
    public void payNotify(JSONObject result) {

        String tradeState = result.getString("trade_state");//交易状态
        String outTradeNo = result.getString("out_trade_no");//本系统订单号
        String transactionId=result.getString("transaction_id");//微信支付交易号

        JSONObject amount = result.getJSONObject("amount");
        String payerTotal=amount.getString("payer_total");//用户支付金额,单位:分

        String successTime=result.getString("success_time");//付款时间

        log.info("接收到了支付回调,状态:{},订单号:{},交易号:{},金额:{},时间:{}",
                tradeState,outTradeNo,transactionId,payerTotal,successTime);

        PaymentRecord paymentRecord=new PaymentRecord();
        paymentRecord.setStatus(tradeState);
        paymentRecord.setOrderId(outTradeNo);
        paymentRecord.setTransactionId(transactionId);
        if(payerTotal!=null){
            if(payerTotal.length()<=2){
                //只有分没有块
                double penny = Double.parseDouble(payerTotal) / 100.00;
                BigDecimal sum=new BigDecimal(penny);
                paymentRecord.setAmount(sum);
            }else {
                //转换成元
                int length = payerTotal.length();
                double penny = Double.parseDouble(payerTotal.substring(length - 2, length)) / 100.00;
                int yuan = Integer.parseInt(payerTotal.substring(0, length - 2));
                BigDecimal yunaDecimal = new BigDecimal(yuan);
                BigDecimal sum = BigDecimalUtil.add(yunaDecimal.doubleValue(), penny);
                paymentRecord.setAmount(sum);
            }
        }
        if(successTime!=null) {
            //转换成date
            String dateStr = successTime.replace("T", " ").replace("+08:00", "");
            Date date = null;
            try {
                date = DateUtils.parseDate(dateStr, "YYYY-MM-dd HH:mm:ss");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            paymentRecord.setSuccessTime(date);
        }
        if(Objects.equals(PayEnum.getPayEnum(tradeState), PayEnum.SUCCESS)){
            //支付成功,发送新订单通知给老板
            try {
                QueryWrapper<Order> q1=new QueryWrapper<>();
                q1.select("order_id","user_id","user_phone","order_status","order_real_price","create_time");
                q1.eq("order_id",outTradeNo);
                Order order = orderService.getOne(q1);
                if(order.getOrderStatus().equals(OrderEnum.FACETO.getCode())){
                    //货到付款订单只需要调用确认收货即可!
                    //自己在这里锁,然后调用收货
                    stringRedisTemplate.opsForValue().set(OrderCommon.doOrderLock+order.getUserId(),"1",10, TimeUnit.SECONDS);
                    orderService.confirmGoods(order);
                }else {
                    //支付订单,发送通知,变为等待送达,然后加入收货延时队列
                    WebSocketServer.sendNewOrderTip();//Vue->发送订单通知
                    //2天23小时50分自动收货
                    orderAcceptDelayQueueUnit.saveBargainDelayItem(new OrderDelayItem(outTradeNo, DateUtils.addMinutes(new Date(), autoConfirmGoodsMin)));
                    order.setOrderId(outTradeNo);
                    order.setOrderStatus(OrderEnum.ING.getCode());
                    orderService.updateById(order);//转为等待送达状态
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error("发送信息失败");
            }
        }
        QueryWrapper<PaymentRecord> q1=new QueryWrapper<>();
        q1.eq("order_id",outTradeNo);
        int count = this.count(q1);
        System.out.println("是否存在:"+count+"-----------------------------------------------------------");
        System.out.println("订单号:"+outTradeNo);
        if(count==0) {
            boolean save = this.save(paymentRecord);
            if(!save)
                log.error("支付记录保存失败");
        } else {
            boolean update = this.updateById(paymentRecord);
            if(!update)
                log.error("支付记录修改失败");
        }
    }

}
